// pages/musics/musics.js
Page({
  data: {
    which: 0,
    playStatu: false,
    height: '',
    // 播放器中的歌曲数据
    playingSong: {
      poster: '',
      name: '',
      author: '',
      src: '',
    },
    // 请求到的歌曲数据
    songs: []
  },
  // 下拉触底事件
  lower() {
    this.getMusicList()
  },
  //点击列表歌曲
  songsTap(e) {
    this.data.playStatu = true
    this.reset()
    let index = e.target.dataset.index;
    this.setData({
      which: index
    })
    this.setData({
      playingSong: this.data.songs[index]
    })
    this.play()
  },
  init() {
    wx.showLoading({
      title: '加载中',
    })
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight - 101
        })
      },
    })
    this.audioCtx = wx.createAudioContext('myAudio')
    let index = this.data.which
    this.getMusicList()
    this.setData({
      playingSong: this.data.songs[index]
    })
    wx.hideLoading()
    this.audioCtx.play()
  },
  onLoad(options) {
    this.init()
  },
  // 请求音乐数据20条
  async getMusicList() {
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
   
   
    wx.hideLoading()
    return 'OK'
  },
  //上一首
  previous() {
    this.data.playStatu = true
    this.setData({
      playStatu: this.data.playStatu
    })
    if (this.data.which > 0) {
      this.reset()
      var index = --this.data.which
      this.setData({
        playingSong: this.data.songs[index]
      })
      this.play()
    } else {
      var index = this.data.which
      wx.showToast({
        title: '已经是第一首了',
        icon: 'error',
        mask: true,
        duration: 1000
      })
    }
  },
  //播放
  play() {
    this.data.playStatu = true
    this.setData({
      playStatu: this.data.playStatu
    })
    this.audioCtx.play()
  },
  //暂停
  pause() {
    this.data.playStatu = false
    this.setData({
      playStatu: this.data.playStatu
    })
    this.audioCtx.pause()
  },
  //回到开头
  reset() {
    this.audioCtx.seek(0)
    this.data.playStatu = false
    this.setData({
      playStatu: this.data.playStatu
    })
  },
  //下一首
  next() {
    this.reset()
    this.data.playStatu = true
    this.setData({
      playStatu: this.data.playStatu
    })
    let index = ++this.data.which
    this.setData({
      playingSong: this.data.songs[index]
    })
    this.play()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})